package com.hexinfo.dmpro.monitor.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hexinfo.dmpro.common.base.Page;
import com.hexinfo.dmpro.common.base.PageResult;
import com.hexinfo.dmpro.monitor.dao.CmImpalaPoolDao;
import com.hexinfo.dmpro.monitor.model.ImpalaPoolModel;
import com.hexinfo.dmpro.monitor.model.base.MonitorReq;
import com.hexinfo.dmpro.monitor.model.cm.*;
import com.hexinfo.dmpro.common.base.BaseService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author peng
 * @date 2022/2/28 14:32
 * 获取IMPALA 信息
 */
@Service
public class CmImpalaService extends BaseService {

    @Autowired
    private CmImpalaResourceService cmImpalaResourceService;

    @Autowired
    private CmImpalaPoolDao cmImpalaPoolDao;

    private String USE_METRIC_NAME = "total_impala_admission_controller_local_backend_mem_usage_across_impala_daemon_pools";
    private String MAX_METRIC_NAME = "impala_admission_controller_pool_max_mem_resources_across_impala_daemon_pools";

    public List<ImpalaResourceInfo> selImpalaPoolTop(ResourceBaseReqModel req){
        //默认查新表，有时间分区就查总表
        List<ImpalaResourceInfo> selImpalaPoolTopList = null;
        Page page = new Page();
        page.setPageIndex(0);
        page.setSize(10);
        page.setSort("id,desc");
        ResourceBaseReqModel reqModel = new ResourceBaseReqModel();
        reqModel.setCmFlag(req.getCmFlag());
        reqModel.setClusterFlag(req.getClusterFlag());
        if(0==req.getTopNum()){
            PageResult pageResult = selImpalaPoolDetail(page, reqModel);
            req.setTopNum((int) pageResult.getTotalElements());
        }
        if ("".equals(req.getStartTime()) || "".equals(req.getEndTime())){
            selImpalaPoolTopList = cmImpalaPoolDao.selImpalaPoolTop(req);
        }else {
            selImpalaPoolTopList = cmImpalaPoolDao.selImpalaPoolTopRange(req);
        }
        return selImpalaPoolTopList;
    }

    /**
     * 查询impala资源池统计信息
     * @return
     */
    public CountResourceInfo selImpalaPoolAllCount(ResourceBaseReqModel req){
        return cmImpalaPoolDao.selImpalaPoolAllCount(req);
    }

    /**
     * 查询impala资源池统计信息
     * @return
     */
    public PageResult selImpalaPoolAll(Page page,ResourceBaseReqModel req){
        return selectPage(cmImpalaPoolDao, "selImpalaPoolYcCount", page, req);
    }

    /**
     * 查询impala资源池异常统计信息
     * @param req
     * @return
     */
    public List<CountResourceInfo> selImpalaPoolYcCount(ResourceBaseReqModel req){
        return cmImpalaPoolDao.selImpalaPoolYcCount(req);
    }

    /**
     * 查询impala资源池异常信息
     * @param req
     * @return
     */
    public PageResult selImpalaPoolYc(Page page,ResourceBaseReqModel req){
        return selectPage(cmImpalaPoolDao, "selImpalaPoolYc", page, req);
    }

    public PageResult selImpalaPoolDetail(Page page, ResourceBaseReqModel req) {
        return selectPage(cmImpalaPoolDao, "selImpalaPoolDetail", page, req);
    }

    public List<ImpalaResourceInfo> selImpalaPoolSyl(ResourceBaseReqModel req){
        return cmImpalaPoolDao.selImpalaPoolSyl(req);
    }

    /**
     * 获取集群资源池信息
     */
    public List<DetailResourceInfo> queryRootPool(String cmFlag,String clusterFlag){
        return cmImpalaPoolDao.queryRootPool(cmFlag,clusterFlag);
    }


    public void getImpalaPool(MonitorReq monitorReq, boolean flag) {
        JSONArray impalaPool = cmImpalaResourceService.getImpalaPool(monitorReq, flag);
        if (impalaPool != null && impalaPool.size() > 0) {
            List<ImpalaPoolModel> impalaPoolModelsAll = new ArrayList<>();
            Map<String,String> maxMap = new HashMap<>();
            JSONObject item = impalaPool.getJSONObject(0);
            if (item != null) {
                JSONArray timeSeries = item.getJSONArray("timeSeries");
                if (timeSeries != null && timeSeries.size() > 0) {
                    for (int i = 0; i < timeSeries.size(); i++) {
                        JSONObject timeSerie = timeSeries.getJSONObject(i);
                        if(timeSerie!=null){
                            ImpalaPoolModel impalaPoolModel = new ImpalaPoolModel();
                            JSONObject metadata = timeSerie.getJSONObject("metadata");
                            JSONArray data = timeSerie.getJSONArray("data");
                            String metricName = metadata.getString("metricName");
                            JSONObject attributes = metadata.getJSONObject("attributes");
                            String poolName = attributes.getString("poolName");
                            impalaPoolModel.setPoolName(poolName);
                            if(USE_METRIC_NAME.equals(metricName)){//使用内存
                                if(data!=null && data.size() >0){
                                    String useB = data.getJSONObject(data.size() - 1).getLong("value").toString();
                                    impalaPoolModel.setUsedB(useB);
                                    impalaPoolModelsAll.add(impalaPoolModel);
                                }
                            }else{//总内存
                                if(data!=null && data.size() >0){
                                    String maxB = data.getJSONObject(data.size() - 1).getJSONObject("aggregateStatistics").getLong("max").toString();
                                    maxMap.put(poolName,maxB);
                                }
                            }
                        }
                    }
                }
            }
            //插入最大值
            if(impalaPoolModelsAll !=null && impalaPoolModelsAll.size()>0){
                impalaPoolModelsAll.forEach(model ->{
                    model.setMaxB(maxMap.get(model.getPoolName()));
                });
            }
            if(flag && impalaPoolModelsAll !=null && impalaPoolModelsAll.size() >0){
                Map<String, Object> map = new HashMap<>();
                map.put("req", monitorReq);
                map.put("list", impalaPoolModelsAll);
                cmImpalaPoolDao.insertPools(map);
                //数据同时存入最新时刻表   处理查询效率慢问题
                cmImpalaPoolDao.deletePoolsNow(map);
                cmImpalaPoolDao.insertPoolsNow(map);
            }
        }
    }
}
